package org.lsb.app_back.interceptor;

import org.lsb.app_back.util.JwtUtil;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的 JWT 令牌
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "无效的令牌");
            return false;
        }

        token = token.substring(7); // 去掉 "Bearer " 前缀

        try {
            // 解析 JWT 令牌
            Map<String,Object> claims=   JwtUtil.parseJwt(token);
            System.out.println(claims);//打印到控制台
            return true; // 校验通过，继续处理请求
        } catch (Exception e) {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "无效的令牌");
            return false; // 校验失败，终止请求
        }
    }
}